<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @drag-sort="sortTable"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="">
        <el-button type="primary" :icon="Download" plain @click="downloadFile">导出</el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- usernameHeader -->
      <template #usernameHeader="scope">
        <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
          {{ scope.column.label }}
        </el-button>
      </template>
      <!-- image -->
      <template #orderPicture="{ row }">
        <el-image
          style="width: 80px; height: 80px"
          :preview-teleported="true"
          :src="row.orderPicture"
          :preview-src-list="[row.orderPicture]"
          fit="cover"
        />
      </template>
      <!-- 判断退款形式 -->
      <template #refundType="{ row }">
        <span v-if="row.refundType === 2" style="color: orange">退货退款</span>
        <span v-if="row.refundType === 1" style="color: #47bdb2">未发货退款</span>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="ChatDotRound" @click="Detail('详情', scope.row)">详情</el-button>
        <el-button type="danger" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <Datils ref="drawerRef" />
  </div>
</template>

<script setup lang="tsx">
import { ref, reactive } from "vue";
import { Order, Refund } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import { useDownloads } from "@/hooks/useDownload";
import { ElMessage, ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import Datils from "@/views/refund/components/datils.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, Download, Upload, View, ChatDotRound, Refresh, Sell, Files } from "@element-plus/icons-vue";
import { OrderById, OrderExport } from "@/api/modules/order";
import { RefundDelte, RefundDownload, RefundPage } from "@/api/modules/refund";
import { showFullScreenLoading, tryHideFullScreenLoading } from "@/components/Loading/fullScreen";

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ type: 1 });

const dataCallback = (data: any) => {
  return {
    list: data.records,
    total: data.total
  };
};

const getTableList = (params: any) => {
  showFullScreenLoading(); // 👈 开启 loading
  let newParams = JSON.parse(JSON.stringify(params));
  tryHideFullScreenLoading(); // 👈 关闭 loading
  return RefundPage(newParams);
};
// 自定义渲染表头（使用tsx语法）
const headerRender = (scope: HeaderRenderScope<Refund>) => {
  return (
    <el-button type="primary" onClick={() => ElMessage.success("我是通过 tsx 语法渲染的表头")}>
      {scope.column.label}
    </el-button>
  );
};

const copyToClipboard = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text);
    ElMessage.success(`已复制`);
  } catch (err) {
    ElMessage.error("复制失败");
  }
};
// 表格配置项
const columns = reactive<ColumnProps<Refund>[]>([
  { type: "selection", fixed: "left", width: 50 },
  { prop: "id", label: "订单id" },
  {
    prop: "orderPicture",
    label: "商品预览图"
  },
  {
    prop: "orderNo",
    label: "订单编号",
    search: { el: "input" },
    render: scope => {
      return (
        <el-button type="primary" link onClick={() => copyToClipboard(scope.row.orderNo.toString())}>
          {scope.row.orderNo}
        </el-button>
      );
    }
  },
  { prop: "refundAmount", label: "退款金额" },
  { prop: "refundReason", label: "退款原因" },
  {
    prop: "refundDate",
    label: "退款时间",
    headerRender
  },
  { prop: "refundType", label: "退款形式" },
  {
    prop: "username",
    label: "退款人",
    search: { el: "input" },
    render: scope => {
      return (
        <el-button type="primary" link onClick={() => copyToClipboard(scope.row.username.toString())}>
          {scope.row.username}
        </el-button>
      );
    }
  },
  { prop: "operation", label: "操作", fixed: "right", width: 200 }
]);

// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log(newIndex, oldIndex);
  console.log(proTable.value?.tableData);
  ElMessage.success("修改列表排序成功");
};

// 删除订单信息
const deleteAccount = async (params: Refund) => {
  await useHandleData(RefundDelte, params.id, `删除${params.username}的用户退款订单`);
  proTable.value?.getTableList();
};

// 导出商品列表
const downloadFile = async () => {
  ElMessageBox.confirm("确认导出退款数据?", "温馨提示", { type: "warning" }).then(() =>
    useDownloads(RefundDownload, "退款列表", proTable.value?.searchParam)
  );
};

const drawerRef = ref<InstanceType<typeof Datils> | null>(null);
const Detail = (title: string, row: Partial<Refund> = {}) => {
  const params = {
    title,
    isView: title === "查看",
    row: { ...row },
    api: undefined,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};
</script>
